<template>
    <div class="sales-product-container">
        <!-- 搜索表单 -->
        <el-form ref="searchFormRef" :model="searchForm" label-width="auto" label-position="left"
            class="sales-product-form">
            <div class="form-row">
                <el-form-item label="客户类别">
                    <el-tree-select v-model="searchForm.type" :data="treeSelectData" filterable clearable
                        style="width: 240px" :props="{ value: 'id', label: 'name', children: 'children' }"
                        :check-strictly="true">

                        <template #default="{ data }">
                            <span>
                                <el-icon>
                                    <Folder v-if="data.children && data.children.length > 0" />
                                    <Document v-else />
                                </el-icon>
                                {{ data.name }}
                            </span>
                        </template>
                    </el-tree-select>
                </el-form-item>

                <el-form-item label="搜索内容">
                    <el-input v-model="searchForm.keyword" clearable placeholder="输入客户编号/名称/联系人/电话/送货地址/备注"
                        style="width: 300px;" />
                </el-form-item>

                <el-form-item label="">
                    <el-checkbox v-model="searchForm.status" @change="handleCheck">显示禁用客户</el-checkbox>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                </el-form-item>
            </div>
        </el-form>

        <!-- 操作按钮 -->
        <div style="gap: 12px; float: right; margin-bottom: 16px;">
            <el-button type="primary" @click="openAddDialog">新增</el-button>
            <el-button @click="batchClose">禁用</el-button>
            <el-button @click="batchOpen">启用</el-button>
            <el-button>导入</el-button>
            <el-button>导出</el-button>
            <el-button @click="batchDelete">删除</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" border style="width: 100%" v-loading="tableLoad"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column label="操作" width="100">
                <template #default="scope">
                    <el-button @click="editCustomer(scope.row.id)" link size="default" icon="Edit" title="编辑" />

                    <el-button @click="deleteCustomer(scope.row.id)" link size="default" icon="Delete" title="删除" />
                </template>
            </el-table-column>

            <el-table-column prop="typeName" label="客户类别" width="140" />
            <el-table-column prop="levelName" label="客户等级" width="140" />
            <el-table-column prop="code" label="客户编号" width="140" />
            <el-table-column prop="name" label="客户名称" width="100" />
            <el-table-column prop="paymentTerms" label="收款条件" width="100"/>
            <el-table-column prop="staffName" label="销售员" width="100" />
            <el-table-column prop="taxCode" label="纳税人识别号" width="180" />
            <el-table-column prop="bank" label="开户银行" width="180" />
            <el-table-column prop="account" label="银行账户" width="180" />
            <el-table-column prop="primaryContactName" label="联系人" width="120" />
            <el-table-column prop="primaryContactPhone" label="联系电话" width="180" />
            <el-table-column prop="primaryContactFax" label="座机" width="100" />
            <el-table-column prop="primaryContactEmail" label="邮箱" width="180" />
            <el-table-column prop="deliveryMethod" label="交货方式" width="100" />
            <el-table-column prop="receivableBalance" label="应收余额" width="100" />
            <el-table-column prop="primaryContactAddress" label="地址" width="180" />
            <el-table-column prop="remark" label="备注" width="120" />
            <el-table-column prop="status" label="状态" width="120">
                <template #default="scope">
                    <el-switch :model-value="scope.row.status" :active-value="1" :inactive-value="0"
                        @change="handleStatus(scope.row)" />
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination v-model:current-page="pageInfo.pageNum" v-model:page-size="pageInfo.pageSize"
            :page-sizes="[5, 10, 15, 20]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total" @size-change="handleSizeChange" @current-change="handleCurrentChange"
            style="float: right;" />


        <!-- 新增客户弹窗 -->
        <el-dialog v-model="dialogVisible" :title="customerDialogType ? '新增客户' : '编辑客户'" width="75%">
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px">

                <!-- 基础信息 -->
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="客户名称" prop="name">
                            <el-input v-model="addForm.name" placeholder="请输入客户名称" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="客户类别" prop="type">
                            <el-tree-select :data="treeSelectData" v-model="addForm.type" placeholder="请选择客户类别"
                                style="width: 100%;" clearable filterable check-strictly
                                :props="{ value: 'id', label: 'name', children: 'children' }">
                                <template #default="{ data }">
                                    <span>
                                        <el-icon>
                                            <Folder v-if="data.children && data.children.length > 0" />
                                            <Document v-else />
                                        </el-icon>
                                        {{ data.name }}
                                    </span>
                                </template>
                            </el-tree-select>
                        </el-form-item>
                    </el-col>

                </el-row>

                <el-row :gutter="20">

                    <el-col :span="12">
                        <el-form-item label="客户等级" prop="level">
                            <el-select v-model="addForm.level" placeholder="请选择客户等级" style="width: 100%;">
                                <el-option v-for="item in levelList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="余额日期" prop="balanceDate">
                            <el-date-picker v-model="addForm.balanceDate" type="date" placeholder="选择日期"
                                format="YYYY-MM-DD" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="期初应收款" prop="initialReceivable" :label-Width="formLabelWidth">
                            <el-input-number v-model="addForm.initialReceivable" :min="0" :precision="2"
                                controls-position="right" placeholder="请输入期初应收款" style="width: 240px" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="期初预收款" prop="initialAdvance" :label-Width="formLabelWidth">
                            <el-input-number v-model="addForm.initialAdvance" :min="0" :precision="2"
                                controls-position="right" placeholder="请输入期初预收款" style="width: 240px" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="业务员" prop="salesman">
                            <el-select v-model="addForm.salesman" placeholder="请选择业务员" style="width: 100%;">
                                <el-option v-for="item in staffList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="交货方式" prop="deliveryMethod">
                            <el-select v-model="addForm.deliveryMethod" placeholder="请选择交货方式" style="width: 100%;"
                                clearable>
                                <el-option v-for="item in deliveryTypes" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="收款条件" prop="paymentTerms">
                            <el-select v-model="addForm.paymentTerms" placeholder="请选择" style="width: 100%;">
                                <el-option :value="1" label="现结" />
                                <el-option :value="2" label="货到付款" />
                                <el-option :value="3" label="分期付款" />
                                <el-option :value="4" label="先款后付" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 发票信息 -->
                <div style="margin-top: 20px; border-top: 1px solid #e4e7ed; padding-top: 15px;">
                    <h3>发票信息</h3>
                </div>

                <el-row :gutter="30">
                    <el-col :span="12">
                        <el-form-item label="纳税人识别号" prop="taxCode">
                            <el-input v-model="addForm.taxCode" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开户银行" prop="bank">
                            <el-input v-model="addForm.bank" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="银行账号" prop="account">
                            <el-input v-model="addForm.account" />
                        </el-form-item>
                    </el-col>
                </el-row>

                <!-- 联系人表格 -->
                <div style="margin-top: 20px; border-top: 1px solid #e4e7ed; padding-top: 15px;">
                    <h3>联系人</h3>
                    <el-table :data="addForm.contacts" style="width: 100%" border height="200">

                        <el-table-column label="操作" width="100" align="center">
                            <template #default="{ $index }">
                                <el-button @click="addContactRow($index)" link size="small" icon="Plus" title="添加联系人" />

                                <el-button @click="removeContact($index)" link size="small" icon="Delete"
                                    title="删除联系人" />
                            </template>
                        </el-table-column>

                        <el-table-column prop="name" label="联系人">
                            <template #default="{ row }">
                                <el-input v-model="row.name" placeholder="姓名" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="phone" label="手机">
                            <template #default="scope">
                                <el-input v-model="scope.row.phone" @blur="() => checkPhone(scope.$index)" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="fax" label="座机">
                            <template #default="{ row }">
                                <el-input v-model="row.fax" placeholder="座机" />
                            </template>
                        </el-table-column>
                        <el-table-column prop="email" label="QQ/微信/Email">
                            <template #default="scope">
                                <el-input v-model="scope.row.email" placeholder="邮箱地址"
                                    @blur="() => checkEmail(scope.$index)" />
                            </template>
                        </el-table-column>

                        <el-table-column label="联系地址">
                            <template #default="{ row }">
                                <div class="address-cell" @click="openAddressDialog(row)">
                                    <span v-if="row.address">{{ row.address }}</span>
                                    <span v-else class="placeholder">点击设置地址</span>
                                </div>
                            </template>
                        </el-table-column>

                        <el-table-column label="首要联系人">
                            <template #default="{ row }">
                                <el-select v-model="row.isFirst" @change="setPrimary(row)" placeholder="请选择">
                                    <el-option label="是" :value="1" />
                                    <el-option label="否" :value="0" />
                                </el-select>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <!-- 备注 -->
                <el-form-item label="备注" prop="remark" style="margin-top: 20px;">
                    <el-input v-model="addForm.remark" type="textarea" :rows="4" />
                </el-form-item>
            </el-form>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="closeDialog">关闭</el-button>
                    <el-button type="primary" @click="submitAddForm" :loading="saving">保存</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 地址编辑对话框 -->
        <el-dialog v-model="addressDialog.visible" title="编辑联系地址" width="420px" @close="closeAddressDialog">
            <el-form label-position="top">
                <!-- 省市区级联 -->
                <el-form-item label="省 / 市 / 区" required>
                    <el-cascader v-model="addressDialog.form.region" :options="regionData" placeholder="请选择省市区"
                        style="width: 100%" size="small" clearable filterable @change="handleRegionChange" />
                </el-form-item>

                <!-- 详细地址 -->
                <el-form-item label="详细地址" required>
                    <el-input v-model="addressDialog.form.detailAddress" placeholder="街道、门牌号、楼栋等" size="small"
                        @input="updateFullAddress" />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="closeAddressDialog">取消</el-button>
                <el-button type="primary" @click="saveAddress" :loading="loading">
                    确定
                </el-button>
            </template>
        </el-dialog>


    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { regionData, codeToText } from 'element-china-area-data'
import axios from 'axios'

const formLabelWidth = '100px'

// 表格加载状态
const tableLoad = ref(false)
// 地址保存加载状态
const loading = ref(false)
// 客户保存加载状态
const saving = ref(false)
// 对话框类型
const customerDialogType = ref(true)

// 搜索表单
const searchForm = ref({
    keyword: '',
    type: null,
    status: 1,
})


const pageInfo = reactive({
    pageNum: 1,
    pageSize: 10,
    total: 0
})

// 对话框状态
const dialogVisible = ref(false)

const addFormRef = ref(null)

// 默认的联系人结构
const defaultContact = {
    name: '',
    phone: '',
    fax: '',
    email: '',
    address: '',
    isFirst: 0 // 默认为非首要
}

// 默认的新增/编辑表单（用于重置）
const defaultAddForm = {
    // 客户信息
    id: null, // 编辑时才有 id
    code: '',
    name: '',
    type: null, // 客户类别 ID
    level: null, // 客户等级 ID
    salesman: null, // 业务员 ID
    balanceDate: null,
    initialReceivable: 0,
    initialAdvance: 0,
    receivableBalance: 0,
    deliveryMethod: null,
    paymentTerms: null,
    remark: '',
    // 开票信息
    taxCode: '',
    bank: '',
    account: '',
    // 联系人信息
    contacts: [{ ...defaultContact, isFirst: 1 }] // 默认第一个为首要
}

const addForm = reactive({ ...defaultAddForm })

// 客户数据
const tableData = ref([])
// 客户类别数据
const customerTypeList = ref([])
// 客户等级
const levelList = ref([])
// 业务员
const staffList = ref([])
// 选中的行
const selections = ref([])

// 构建树形数据
const treeData = computed(() => {
    const roots = []

    const map = {}

    customerTypeList.value.forEach(item => {
        map[item.id] = { ...item, children: [] }
    })

    customerTypeList.value.forEach(item => {
        if (item.parentId == null || item.parentId == '0') {
            roots.push(map[item.id])
        } else {
            const parentObj = map[item.parentId]
            if (parentObj) {
                parentObj.children.push(map[item.id])
            }
        }
    })
    return roots
})

// 树选择器
const treeSelectData = computed(() => {
    const enabledTreeData = treeData.value
    return [
        {
            id: '0',
            name: '全部',
            children: enabledTreeData
        }
    ]
})

// 选中的id
const selectionIds = computed(() => selections.value.map(item => item.id))


// 地址对话框状态
const addressDialog = reactive({
    visible: false,
    currentContact: null,
    form: {
        region: [],
        detailAddress: '',
        fullAddress: ''
    }
})

// 手机号正则
const phonePattern = /^1[3-9]\d{9}$/
// 邮箱正则
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

// 联系人手机校验
const checkPhone = (index) => {
    const value = addForm.contacts[index]?.phone

    if (!value || value.trim() === '') {
        return true
    }
    if (!phonePattern.test(value)) {
        ElMessage.warning('请输入正确的手机号码')
        return false
    }
    return true
}

// 联系人邮箱校验
const checkEmail = (index) => {
    const value = addForm.contacts[index]?.email
    if (!value || value.trim() === '') {
        return true
    }
    if (!emailPattern.test(value)) {
        ElMessage.warning('请输入正确的邮箱地址')
        return false
    }
    return true
}

// 表单验证规则
const addFormRules = {
    code: [{ required: true, message: '请输入客户编号', trigger: 'blur' }],
    name: [{ required: true, message: '请输入客户名称', trigger: 'blur' }],
    type: [{ required: true, message: '请选择客户类别', trigger: 'change' }],
    level: [{ required: true, message: '请选择客户等级', trigger: 'change' }]
}

// 获取客户信息
const getCustomerList = async () => {
    tableLoad.value = true
    try {
        const params = {
            pageNum: pageInfo.pageNum,
            pageSize: pageInfo.pageSize,
            ...searchForm.value
        }

        const res = await axios.get('/api/basic/customer/customerByPage', { params })
        if (res.data.code === 5200) {
            tableData.value = res.data.pageInfo.list
            pageInfo.total = res.data.pageInfo.total
            pageInfo.pageNum = res.data.pageInfo.pageNum
        } else {
            ElMessage.error(res.data.message)
        }
    } catch (error) {
        console.error('加载客户列表失败:', error)
        ElMessage.error('加载客户列表失败: ' + (error.response?.data?.msg || error.message))
    } finally {
        tableLoad.value = false
    }
}

// 获取客户类别
const getCustomerType = async () => {
    const res = await axios.get('/api/basic/customer/allCustomerTypes')
    if (res.data.code === 5200) {
        customerTypeList.value = res.data.customerTypeList
    }
}

// 获取客户等级
const getLevelList = async () => {
    try {
        const res = await axios.get('/api/basic/customer/customerLevels')
        if (res.data.code === 5200) {
            levelList.value = res.data.customerLevels
        } else {
            ElMessage.error(res.data.message)
        }
    } catch (error) {
        console.error('加载等级列表失败:', error)
        ElMessage.error('加载等级列表失败: ' + (error.response?.data?.msg || error.message))
    }
}

// 获取业务员
const getStaffList = async () => {
    try {
        const res = await axios.get('/api/basic/enterprise/allStaff')
        if (res.data.code === 5200) {
            staffList.value = res.data.staffList
        } else {
            ElMessage.error(res.data.message)
        }
    } catch (error) {
        console.error('加载业务员列表失败:', error)
        ElMessage.error('加载业务员列表失败: ' + (error.response?.data?.msg || error.message))
    }
}

//  交货方式
const deliveryTypes = [
    { value: '1', label: '快递物流' },
    { value: '2', label: '自配送' },
    { value: '3', label: '自提' },
    { value: '4', label: '其他' }
]

// 搜索
const handleSearch = () => {
    pageInfo.pageNum = 1
    getCustomerList()
}

// 页面容量变化
const handleSizeChange = (val) => {
    pageInfo.pageSize = val
    pageInfo.pageNum = 1
    getCustomerList()
}

// 页码变化
const handleCurrentChange = (val) => {
    pageInfo.pageNum = val
    getCustomerList()
}

// 状态选择
const handleCheck = (checked) => {
    searchForm.value.status = checked ? null : 1
    getCustomerList()
}

// 切换状态
const handleStatus = async (row) => {
    tableLoad.value = true
    customerDialogType.value = true
    const originalStatus = row.status
    try {
        const res = await axios.post("/api/basic/customer/updateCustomerStatus", null, { params: { id: row.id, status: originalStatus === 1 ? 0 : 1 } })
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getCustomerList()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        tableLoad.value = false
    }
}

// 选中多选框
const handleSelectionChange = (selection) => {
    selections.value = selection
}

// 批量禁用
const batchClose = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(0)
}

// 批量启用
const batchOpen = async () => {
    if (selectionIds.value.length === 0) {
        ElMessage.warning('请先选择')
        return
    }
    await batchUpdateStatus(1)
}

// 批量修改状态
const batchUpdateStatus = async (status) => {

    const params = {
        ids: selectionIds.value,
        status
    }

    try {
        const res = await axios.post("/api/basic/customer/batchUpdateCustomerStatus", params)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getCustomerList()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 删除
const deleteCustomer = async (id) => {
    try {
        const res = await axios.post("/api/basic/customer/deleteCustomer", null, { params: { id } })
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getCustomerList()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}


// 批量删除
const batchDelete = async () => {
    try {
        const res = await axios.post("/api/basic/customer/batchDeleteCustomer", selectionIds.value)
        if (res.data.code === 5200) {
            ElMessage.success(res.data.msg)
            await getCustomerList()
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    }
}

// 打开弹窗
const openAddDialog = async () => {
    resetAddForm()
    dialogVisible.value = true
    customerDialogType.value = true
    await getStaffList()
    await getLevelList()
}

// 编辑客户
const editCustomer = async (id) => {
    customerDialogType.value = false
    resetAddForm()

    dialogVisible.value = true
    tableLoad.value = true

    try {
        const res = await axios.get('/api/basic/customer/customerById', { params: { id: id } })
        if (res.data.code === 5200) {
            const customerResponse = res.data.customerResponse
            const customer = customerResponse.customer
            const contactList = customerResponse.contactList

            Object.assign(addForm, {
                id,
                code: customer.code,
                name: customer.name,
                type: customer.type,
                level: customer.level,
                salesman: customer.salesman,
                balanceDate: customer.balanceDate ? new Date(customer.balanceDate) : null,
                initialReceivable: customer.initialReceivable,
                initialAdvance: customer.initialAdvance,
                receivableBalance: customer.receivableBalance,
                deliveryMethod: customer.deliveryMethod,
                paymentTerms: customer.paymentTerms,
                remark: customer.remark,
                taxCode: customer.taxCode,
                bank: customer.bank,
                account: customer.account,
                contacts: contactList.map(c => ({
                    name: c.name,
                    phone: c.phone,
                    fax: c.fax,
                    email: c.email,
                    address: c.address,
                    isFirst: c.isFirst
                }))
            })

            await getStaffList()
            await getLevelList()
            dialogVisible.value = true
        } else {
            ElMessage.error(res.data.msg)
        }
    } catch (error) {
        ElMessage.error(error.message)
    } finally {
        tableLoad.value = false
    }
}

// 保存客户信息
const submitAddForm = async () => {
    try {
        await addFormRef.value.validate()

        // 检查联系人信息
        let hasError = false;
        addForm.contacts.forEach((contact, index) => {
            if (!checkPhone(index)) hasError = true;
            if (!checkEmail(index)) hasError = true;
        });
        if (hasError) {
            return;
        }
    } catch (error) {
        ElMessage.error('请检查表单填写是否正确')
        return
    }

    // 过滤空联系人
    const validContacts = addForm.contacts.filter(contact =>
        contact.name || contact.phone || contact.fax || contact.email || contact.address
    )

    // 检查是否至少有一个有效联系人
    if (validContacts.length === 0) {
        ElMessage.warning('请至少添加一个有效的联系人信息')
        return
    }

    // 检查是否有首要联系人
    const hasPrimary = validContacts.some(contact => contact.isFirst === 1)
    if (!hasPrimary && validContacts.length > 0) {
        // 如果没有设置首要联系人，自动设置第一个为首要
        validContacts[0].isFirst = 1
        ElMessage.info('已自动设置第一个联系人为首要联系人')
    }

    // 构造请求体 - 匹配后端的CustomerRequest结构
    const customerRequest = {
        customer: {
            id: addForm.id,
            name: addForm.name,
            type: addForm.type,
            level: addForm.level,
            salesman: addForm.salesman,
            balanceDate: addForm.balanceDate,
            initialReceivable: addForm.initialReceivable || 0,
            initialAdvance: addForm.initialAdvance || 0,
            receivableBalance: addForm.receivableBalance,
            taxCode: addForm.taxCode,
            bank: addForm.bank,
            account: addForm.account,
            deliveryMethod: addForm.deliveryMethod,
            paymentTerms: addForm.paymentTerms,
            remark: addForm.remark,
        },
        contactList: validContacts.map(contact => ({
            name: contact.name || '',
            phone: contact.phone || '',
            fax: contact.fax || '',
            email: contact.email || '',
            address: contact.address || '',
            isFirst: contact.isFirst === 1 ? 1 : 0
        }))
    }

    try {
        saving.value = true

        const url = customerDialogType.value ? '/api/basic/customer/addCustomer' : '/api/basic/customer/updateCustomer'

        const res = await axios.post(url, customerRequest)
        if (res.data.code === 5200) {
            ElMessage.success('客户创建成功！')
            dialogVisible.value = false
            resetAddForm()
            // 刷新列表
            pageInfo.pageNum = 1
            getCustomerList()
        } else {
            ElMessage.error(res.data.message || '创建失败')
        }
    } catch (error) {
        console.error('创建客户失败:', error)
        ElMessage.error('创建失败: ' + (error.response?.data?.message || error.message))
    } finally {
        saving.value = false
    }
}

// 重置表单
const resetAddForm = () => {
    Object.assign(addForm, {
        id: null,
        code: '',
        name: '',
        type: '',
        level: '',
        salesman: '',
        balanceDate: null,
        initialReceivable: null,
        initialAdvance: null,
        deliveryMethod: null,
        receivableBalance: null,
        paymentTerms: '',
        remark: '',
        taxCode: '',
        bank: '',
        account: '',
        contacts: [
            {
                name: '',
                phone: '',
                fax: '',
                email: '',
                address: '',
                isFirst: 1
            }
        ]
    })

    // 重置表单验证状态
    if (addFormRef.value) {
        addFormRef.value.clearValidate()
    }
}


// 在当前行后添加联系人
const addContactRow = (index) => {
    addForm.contacts.splice(index + 1, 0, {
        name: '',
        phone: '',
        fax: '',
        email: '',
        address: '',
        isFirst: null
    })
}

// 删除联系人
const removeContact = (index) => {
    if (addForm.contacts.length > 1) {
        addForm.contacts.splice(index, 1)
        ElMessage.success('联系人已删除')
    } else {
        ElMessage.warning('至少需要保留一个联系人')
    }
}

// 设置首要联系人
const setPrimary = (currentRow) => {
    addForm.contacts.forEach(item => {
        item.isFirst = (item === currentRow) ? 1 : 0
    })
}

// 打开地址对话框（支持回显）
const openAddressDialog = (contact) => {
    addressDialog.currentContact = contact

    if (contact.address) {
        const parsedData = parseExistingAddress(contact.address)
        addressDialog.form = {
            region: parsedData.region || [],
            detailAddress: parsedData.detailAddress || '',
            fullAddress: contact.address
        }
    } else {
        addressDialog.form = {
            region: [],
            detailAddress: '',
            fullAddress: ''
        }
    }
    addressDialog.visible = true
}

// 解析现有地址
const parseExistingAddress = (address) => {
    if (!address) return { region: [], detailAddress: '' }

    try {
        const parts = address.split(' ')
        if (parts.length >= 3) {
            const provinceName = parts[0]
            const cityName = parts[1]
            const districtName = parts[2]
            const detailAddress = parts.slice(3).join(' ') || ''

            const regionCodes = findRegionCodes(provinceName, cityName, districtName)
            return { region: regionCodes, detailAddress }
        }
        return { region: [], detailAddress: address }
    } catch (error) {
        return { region: [], detailAddress: address }
    }
}

// 查找地区代码
const findRegionCodes = (provinceName, cityName, districtName) => {
    try {
        for (const province of regionData) {
            if (codeToText[province.value] === provinceName) {
                if (province.children) {
                    for (const city of province.children) {
                        if (codeToText[city.value] === cityName) {
                            if (city.children) {
                                for (const district of city.children) {
                                    if (codeToText[district.value] === districtName) {
                                        return [province.value, city.value, district.value]
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return []
    } catch (error) {
        return []
    }
}

// 安全处理地区选择变化
const handleRegionChange = (value) => {
    try {
        addressDialog.form.region = Array.isArray(value) ? value : []
        updateFullAddress()
    } catch (error) {
        console.error('处理地区选择变化失败:', error)
        addressDialog.form.region = []
    }
}

// 安全更新完整地址
const updateFullAddress = () => {
    try {
        const { region, detailAddress } = addressDialog.form

        addressDialog.form.fullAddress = detailAddress || ''

        if (!region || region.length !== 3) {
            return
        }

        const provinceCode = region[0]
        const cityCode = region[1]
        const districtCode = region[2]

        if (!provinceCode || !cityCode || !districtCode) {
            return
        }

        const province = codeToText[provinceCode] || ''
        const city = codeToText[cityCode] || ''
        const district = codeToText[districtCode] || ''

        if (!province || !city || !district) {
            return
        }

        const regionText = `${province} ${city} ${district}`
        addressDialog.form.fullAddress = detailAddress ?
            `${regionText} ${detailAddress}`.trim() : regionText

    } catch (error) {
        console.error('生成完整地址失败:', error)
        addressDialog.form.fullAddress = addressDialog.form.detailAddress || ''
    }
}

// 保存地址
const saveAddress = async () => {
    try {
        loading.value = true

        if (!addressDialog.form.region || addressDialog.form.region.length !== 3) {
            ElMessage.error('请选择完整的省市区')
            return
        }

        if (!addressDialog.form.detailAddress?.trim()) {
            ElMessage.error('请输入详细地址')
            return
        }

        if (addressDialog.currentContact) {
            Object.assign(addressDialog.currentContact, {
                address: addressDialog.form.fullAddress.trim()
            })

            ElMessage.success('地址保存成功')
            closeAddressDialog()
        }

    } catch (error) {
        console.error('保存地址失败:', error)
        ElMessage.error('保存失败: ' + (error.message))
    } finally {
        loading.value = false
    }
}

// 关闭地址对话框
const closeAddressDialog = () => {
    addressDialog.visible = false
    resetAddressForm()
}

// 重置地址表单
const resetAddressForm = () => {
    addressDialog.form = {
        region: [],
        detailAddress: '',
        fullAddress: ''
    }
    addressDialog.currentContact = null
}

const closeDialog = () => {
    ElMessageBox.confirm('当前有未保存的内容，确定关闭吗？')
        .then(() => {
            dialogVisible.value = false
            resetAddForm()
        })
        .catch(() => { })
}

// 生命周期
onMounted(() => {
    getCustomerList()
    getCustomerType()
})

</script>


<style scoped>
.sales-product-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
}

.sales-product-form {
    max-width: 1200px;
}

.form-row {
    display: flex;
    gap: 15px;
    flex-wrap: nowrap;
    margin-bottom: 20px;
    align-items: flex-start;
}

.form-row .el-form-item {
    flex: 1;
    min-width: 240px;
}

.el-form-item__label {
    font-weight: normal;
    color: #666;
    margin-right: 10px;
}

.el-form-item__content {
    display: flex;
    align-items: center;
}

.el-input__inner,
.el-select .el-input__inner {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
    height: 32px;
}

.el-input__inner:focus {
    border-color: #409eff;
    outline: none;
}

.address-cell {
    padding: 8px;
    cursor: pointer;
    border: 1px solid transparent;
    border-radius: 4px;
    transition: all 0.3s ease;
    min-height: 32px;
    display: flex;
    align-items: center;
}

.address-cell:hover {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
}

.placeholder {
    color: #c0c4cc;
    font-style: italic;
}

/* 响应式 */
@media (max-width: 768px) {
    .form-row {
        flex-direction: column;
    }

    .form-row .el-form-item {
        min-width: 100%;
    }

    .el-row {
        flex-direction: column;
    }
}
</style>